<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :close-func="closeFunc"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
    <div :style="{ display: 'flex', justifyContent: 'center' }">
      <Transfer
        v-model:target-keys="selectOptions"
        :rowKey="(record) => record.id"
        :render="(item) => item.roleName"
        :titles="['未分配角色', '已分配角色']"
        :data-source="dataOptions"
    /></div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { Transfer } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { outSchema } from './data';
  import { getUserAuthApi, saveUserAuthApi } from '@/api/system/user';
  import { getRoleAllApi } from '@/api/system/role';
  // import { addWorkflowCategoryApi, updateWorkflowCategoryApi } from '@/api/workflow/category';
  // import type { WorkflowCategoryItem } from '@/api/workflow/model/categoryModel';

  const rowId = ref();
  const selectOptions = ref([]);
  const dataOptions = ref([]);
  const getTitle = ref('用户授权');

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: outSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    setFieldsValue({ ...data });
    // console.log(data);
    const datares = await getRoleAllApi({ roleStatus: 0 });
    rowId.value = data.id;
    dataOptions.value = datares;
    const selres: any = await getUserAuthApi(data.id);
    const arr: any = [];
    selres.map((item) => {
      arr.push(item.id);
    });
    selectOptions.value = arr;
  });

  // const getTitle = computed(() => (!unref(rowId) ? '新增用户' : '编辑用户'));

  const closeFunc = async () => {
    await resetFields();
    return true;
  };

  async function handleSubmit() {
    try {
      // const values = await validate();
      console.log(selectOptions.value, rowId);
      setModalProps({ confirmLoading: true });
      // TODO custom api
      const params = {
        userId: rowId.value,
        roleIds: selectOptions.value,
      };
      // console.log(params);
      const res = await saveUserAuthApi(params);
      console.log(res);
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
